<template>
  <div class="information-wrapper">
    <!-- 头部信息 -->
    <div class="header-wrapper">
      <yd-navbar title="订单信息" height='40px' fontsize='16px'>
        <router-link to="/goods" slot="left">
          <yd-navbar-back-icon></yd-navbar-back-icon>
        </router-link>
      </yd-navbar>
    </div>
    <!-- 头部信息 -->
    <!-- 折叠面板内容 -->
    <div class="content-wrapper">
      <yd-accordion accordion v-for="(item,index) in countData" :key="index">
        <yd-accordion-item :title="item[0].productname+'类'">
          <div style="padding: .24rem;" class="erji">
            <yd-accordion accordion v-for="(ele,key) in item" :key="key">
              <div class="bgc">
                <yd-accordion-item :title="ele.productname">
                  <div class="mian">
                    <group>
                      <div class="leixing">
                      <popup-radio title="类型" :options="typeOptions" v-model="ele.type">
                        <p slot="popup-header" class="demo3-slot vux-1px ff">请选择使用类型</p>
                      </popup-radio>
                      </div>
                      <popup-radio title="开门方向" :options="dirOptions" v-model="ele.direction" @on-hide=disabledParts(ele)>
                        <p slot="popup-header" class="demo3-slot vux-1px ff">请选择开门方向</p>
                      </popup-radio>
                      <x-input title="主材单价" readonly  placeholder="单价(元/㎡)"   v-model="ele.price+'元/m²'" text-align="right"></x-input>
                      <x-input class="vux-1px-b" title="高度" type='text'  placeholder="请输入高度(单位：mm)" :show-clear="false"  v-model="ele.height" text-align="right" @on-change='clickHeight(ele)'></x-input>
                      <div class="width">
                        <span class="width-left">宽度</span>
                        <input  class="width-right" type="text" placeholder="请输入宽度(单位：mm)"  v-model="ele.width" @change="clickWidth(ele)">
                      </div>
                      <popup-picker :disabled=ele.disabled title="拉手类型" :data="handleType" v-model="ele.parts" @on-change="changeParts(ele)" placeholder="请选择拉手类型"></popup-picker>
                      <x-input class="vux-1px-b" title="拉手单价"  type='number' readonly  placeholder="单价(元/m)" :show-clear="false"  v-model="ele.lashou" text-align="right"></x-input>
                      <div class="width">
                        <span class="width-left">数量</span>
                        <input  class="width-right" type="text" placeholder="请输入您需要的数量"  v-model="ele.count" @change="clickCount(ele)">
                      </div>
                      <x-input title="小计" readonly type='number'  :show-clear="false"  v-model="ele.xiaoji" text-align="right"></x-input>
                    </group>
                  </div>
                </yd-accordion-item>
              </div>
            </yd-accordion>
            <div class="mar-t10"></div>
          </div>
        </yd-accordion-item>
      </yd-accordion>
    </div>
    <!-- 折叠面板内容 -->
    <!-- 信息汇总 -->
    <div class="total-wrapper">
      <div class="total-left">
        <div>总板数</div>
        <div class="total-bottom">{{totalnum}}块</div>
      </div>
      <div class="total-center">
        <div v-if="totalarea<=0">
          <div>
            总面积
          </div>
          <div class="total-bottom">
            0m²
          </div>
        </div>
        <div v-else>
          <div>
            总面积
          </div>
          <div class="total-bottom">
            {{totalarea}}m²
          </div>
        </div>
      </div>
      <div class="total-right">
        <div v-if="totalPrice<=0">
          <div>
            总计
          </div>
          <div class="total-bottom">0元</div>
        </div>
        <div v-else>
          <div>
            总计
          </div>
          <div class="total-bottom">
            {{totalPrice}}元
          </div>
        </div>
      </div>
    </div>
    <!-- 信息汇总 -->
    <!-- 用户信息 -->
    <div class="userInfo-wrapper">
      <div class="name-wrapper">
        <span slot="left">姓名：</span>
        <input slot="right" v-model="name" placeholder="请输入寄送人姓名">
      </div>
      <div class="tel-wrapper">
        <span slot="left">手机号：</span>
        <input slot="right" v-model="tel" placeholder="请输入手机号码" type="number" oninput="if(value.length>11)value=value.slice(0,11)">
      </div>
      <div class="adress-wrapper">
        <yd-cell-group>
          <yd-cell-item arrow>
            <span slot="left">所在地区：</span>
            <input slot="right" type="text" @click.stop="isShowAddress = true" v-model="adress" readonly placeholder="请选择收货地址">
          </yd-cell-item>
        </yd-cell-group>
        <yd-cityselect v-model="isShowAddress" :callback="result" :items="district"></yd-cityselect>
        <div class="datail-wrapper">
          <span slot="left">街道地址：</span>
          <input slot="right" v-model="datail" placeholder="请输入街道地址">
        </div>
      </div>
    </div>
    <!-- 用户信息 -->
    <div class="btn-wrapper">
      <yd-button size="large" type="primary" @click.native="sendForm" :disabled='isDisabled'>提交</yd-button>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import { Group, PopupRadio, Cell, XInput, PopupPicker } from "vux";
import District from "ydui-district/dist/jd_province_city_area_id";
import apis from "../../../static/js/api.js";
export default {
  components: {
    Group,
    PopupRadio,
    Cell,
    XInput,
    PopupPicker
  },
  data() {
    return {
      typeOptions: ["地柜", "吊柜"],
      dirOptions: ["左开", "右开", "不开", "见光", "拉篮", "假门","上翻门"],
      name: "",
      tel: "",
      isShowAddress: false,
      adress: "云南 昆明市 官渡区",
      district: District,
      datail: "",
      price: 0,
      flag: true,
      isDisabled: false,
      selectedfoods: [],
      countData: [],
      listData: [],
      orderInfo: {},
      handleType: [],
      arr: [],
      wxuserinfoid: ''
    };
  },
  computed: {
    // 总价
    totalPrice() {
      let totalPrice = 0;
      this.countData.forEach(item => {
        item.forEach(ele => {
          totalPrice += ele.xiaoji;
        });
        totalPrice = this.toDecimal(totalPrice);
      });
      return totalPrice;
    },
    totalarea() {
      let totalarea = 0;
      this.countData.forEach(item => {
        item.forEach(ele => {
          totalarea += ele.width / 1000 * (ele.height / 1000);
        });
        totalarea = this.toDecimal(totalarea);
      });
      return totalarea;
    },
    totalnum() {
      let totalnum = 0;
      this.countData.forEach(item => {
        item.forEach(ele => {
          totalnum += parseInt(ele.count);
        });
        totalnum = this.toDecimal(totalnum);
      });
      return totalnum;
    }
  },
  watch: {
    // 监听路由参数变化
    $route(to, from) {
      if (this.$route.query.selectFoods) {
        this.countData = [];
        this.getUrl();
      }
    }
  },
  created() {
    //获取用户信息
    this.wxuserinfoid = JSON.parse(window.localStorage.getItem("userInfo")).wxuserinfo.id;
    console.log(this.wxuserinfoid)
    // 获取路由参数+获取把手信息
    this.getInfo();
  },
  methods: {
    getInfo() {
      // apis
      this.$vux.loading.show({
        text: "正在加载"
      });
      this.$axios
        .post(`${apis}/app/order/getflist`, this.confusion(JSON.stringify({})), {
          headers: {
            Authorization:
              "Bearer " +
              JSON.parse(window.localStorage.getItem("userInfo")).token,
            "Content-Type": "application/json;charset=UTF-8",
            "Cache-Control": "no-cache",
            isApp: "isApp"
          }
        })
        .then(response => {
          this.$vux.loading.hide();
          this.arr = response.data;
          var listArr = [];
          this.arr.forEach(ele => {
            let str = ele.name;
            listArr.push(str);
          });
          this.handleType.push(listArr);
          this.getUrl();
        })
        .catch(error => {
          this.$vux.loading.hide();
          console.log(error);
          this.$dialog.toast({
            mes: "服务器异常"
          });
        });
    },
    // 路由参数处理
    getUrl() {
      this.selectedfoods = JSON.parse(this.$route.query.selectFoods);
      for (let i = 0; i < this.selectedfoods.length; i++) {
        let arr = [];
        for (let n = 0; n < this.selectedfoods[i].count; n++) {
          let list = {
            id: this.selectedfoods[i].id,
            productname: this.selectedfoods[i].productname,
            price: this.selectedfoods[i].price,
            typename: this.selectedfoods[i].typename,
            width: null,
            height: null,
            type: "",
            direction: "",
            parts: [],
            arr: this.arr,
            lashou: null,
            xiaoji: "0",
            count: "1",
            disabled: false
          };
          arr.push(list);
        }
        this.countData.push(arr);
      }
    },
    // 获取地区值
    result(ret) {
      this.adress = ret.itemName1 + " " + ret.itemName2 + " " + ret.itemName3;
    },
    // 填写高度
    clickHeight(ele) {
      ele.xiaoji = this.toDecimal(
        ele.width / 1000 * ele.height / 1000 * ele.price * ele.count +
          ele.width / 1000 * ele.lashou * ele.count
      );
    },
    // 填写宽度
    clickWidth(ele) {
      ele.xiaoji = this.toDecimal(
        ele.width / 1000 * ele.height / 1000 * ele.price * ele.count +
          ele.width / 1000 * ele.lashou * ele.count
      );
    },
    clickCount(ele) {
      ele.xiaoji = this.toDecimal(
        ele.width / 1000 * ele.height / 1000 * ele.price * ele.count +
          ele.width / 1000 * ele.lashou * ele.count
      );
    },
    // 选择开门方向为见光时，拉手不可选
    disabledParts(ele) {
      if (ele.direction === "见光") {
        ele.disabled = true;
        ele.parts = [];
        ele.lashou = null;
      } else {
        ele.disabled = false;
      }
    },
    // 选择把手类型
    changeParts(ele) {
      let curindex = null;
      ele.arr.forEach((item, index) => {
        if (item.name === ele.parts[0]) {
          curindex = index;
        }
      });
      ele.lashou = ele.arr[curindex].price;
      ele.xiaoji = this.toDecimal(
        ele.width / 1000 * ele.height / 1000 * ele.price * ele.count +
          ele.width / 1000 * ele.lashou * ele.count
      );
    },
    // 生成5位随机数
    RndNum(n) {
      let rnd = "";
      for (let i = 0; i < n; i++) {
        rnd += Math.floor(Math.random() * 10);
      }
      return rnd;
    },
    // 返回当前日期字符串
    getNowFormatDate() {
      let date = new Date();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      let currentdate = date.getFullYear().toString() + month.toString() + strDate.toString();
      return currentdate;
    },
    // 保留两位小数
    // 功能：将浮点数四舍五入，取小数点后2位
    toDecimal(num) {
      var f = parseFloat(num);
      if (isNaN(f)) {
        return;
      }
      f = Math.round(num * 100) / 100;
      return f;
    },
    // 提交表单
    sendForm() {
      var sendArr = [];
      this.countData.forEach(item1 => {
        item1.forEach(item2 => {
          sendArr.push(item2);
        });
      });
      this.listData = sendArr;
      this.flag = false;
      this.listData.forEach(ele => {
        if (
          ele.width === null &&
          ele.height === null &&
          ele.type === "" &&
          ele.direction === "" &&
          ele.lashou === null
        ) {
          this.flag = true;
        }
      });
      if (this.flag) {
        this.$dialog.toast({
          mes: "还有表单未填写"
        });
        return false;
      }
      let reg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/; // 验证手机号正则
      if (this.name === "") {
        this.$dialog.toast({
          mes: "请填写您的姓名"
        });
        return false;
      } else if (this.tel === "") {
        this.$dialog.toast({
          mes: "请填写你您的电话"
        });
      } else if (this.adress === "" && this.datail === "") {
        this.$dialog.toast({
          mes: "请填写您的地址"
        });
      } else if (this.adress === "") {
        this.$dialog.toast({
          mes: "请选择您的地址"
        });
      } else if (this.datail === "") {
        this.$dialog.toast({
          mes: "请填写您的地址"
        });
      } else {
        if (!reg.test(this.tel)) {
          this.$dialog.alert({
            mes: "手机格式不正确"
          });
        } else {
          let rod = this.RndNum(5);
          let date = this.getNowFormatDate();
          let num = date + "" + rod;
          this.orderInfo.list = this.listData;
          this.orderInfo.name = this.name;
          this.orderInfo.tel = this.tel;
          this.orderInfo.address = this.adress;
          this.orderInfo.addressDetail = this.datail;
          this.orderInfo.totalPrice = this.totalPrice;
          this.orderInfo.totalarea = this.totalarea;
          this.orderInfo.totalnum = this.totalnum;
          this.orderInfo.num = num;
          this.orderInfo.wxuserinfoid = this.wxuserinfoid
          this.$vux.loading.show({
            text: "正在加载"
          });
          this.$axios
            .post(
              `${apis}/app/order/add`,
              this.confusion(
                JSON.stringify({
                  orderInfo: this.orderInfo
                })
              ),
              {
                headers: {
                  Authorization:
                    "Bearer " +
                    JSON.parse(window.localStorage.getItem("userInfo")).token,
                  "Content-Type": "application/json;charset=UTF-8",
                  "Cache-Control": "no-cache",
                  isApp: "isApp"
                }
              }
            )
            .then(response => {
              this.$vux.loading.hide();
              console.log("这是提交的数据", this.listData);
              let that = this;
              this.$dialog.toast({
                mes: "提交成功",
                callback: () => {
                  that.$router.push({
                    path: "/pay",
                    query: {
                      totalPrice: this.totalPrice
                    }
                  });
                }
              });
            })
            .catch(error => {
              this.$vux.loading.hide();
              console.log(error);
              this.$dialog.toast({
                mes: "服务器异常"
              });
            });
        }
      }
    }
  }
};
</script>

<style scoped>
.bgc {
  background-color: #f7f7f7;
}
.information-wrapper {
  position: fixed;
  overflow: scroll;
  width: 100%;
  height: 100%;
  background-color: #fff;
}
.header-wrapper {
  position: fixed;
  top: 0;
  width: 100%;
}
.erji >>> .yd-accordion-head {
  padding: 0 20px;
}
.content-wrapper {
  margin-top: 40px;
  background-color: #000;
}
.information-wrapper >>> .weui-cells {
  margin-top: 0;
  padding: 0 !important;
  font-size: 14px;
  border: none;
}
.mian >>> .vux-1px-b:after {
  left: 15px;
}
.leixing >>> .weui-cel {
  padding: 15px;
}
.ff >>> .weui-cells {
  padding: 15px 10px;
}
.information-wrapper >>> .vux-cell-primary {
  font-size: 14px;
}
.title {
  padding-left: 12px;
  line-height: 30px;
  text-align: center;
}
.demo3-slot {
  text-align: center;
  color: #888;
  line-height: 40px;
}
.width {
  display: flex;
  padding: 10px 15px;
}
.width-left,
.width-right {
  flex: 1;
}
.width-right {
  text-align: right;
}
.total-wrapper {
  display: flex;
  margin-top: 20px;
  margin-bottom: -50px;
  font-size: 14px;
  border-bottom: 1px solid #e1e1e1;
}
.total-left {
  flex: 1;
  text-align: center;
}
.total-center {
  flex: 1;
  text-align: center;
}
.total-right {
  flex: 1;
  text-align: center;
}
.total-bottom {
  margin-top: 6px;
  margin-bottom: 10px;
}
.userInfo-wrapper {
  flex: 1;
  margin-top: 50px;
}
.information-wrapper >>> .yd-cell-right .yd-datetime-input,
.yd-cell-right input[type="date"],
.yd-cell-right input[type="datetime-local"],
.yd-cell-right input[type="email"],
.yd-cell-right input[type="number"]:not(.yd-spinner-input),
.yd-cell-right input[type="password"],
.yd-cell-right input[type="tel"],
.yd-cell-right input[type="text"],
.yd-cell-right input[type="time"],
.yd-cell-right input[type="url"] {
  height: 40px;
}
.information-wrapper >>> .yd-cell-right {
  min-height: 40px;
}
.information-wrapper >>> .yd-cell-left,
.yd-cell-right {
  font-size: 14px;
}
.name-wrapper {
  padding: 0 16px;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #e1e1e1;
}
.tel-wrapper {
  padding: 0 16px;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #e1e1e1;
}
.datail-wrapper {
  box-sizing: border-box;
  margin-top: -20px;
  margin-bottom: 60px;
  padding: 0 15px;
  padding-top: 4px;
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #e1e1e1;
}
</style>
